package io.github.flypiggy.stack.operate.log.spring.boot.starter.datasource.impl;

import io.github.flypiggy.stack.operate.log.spring.boot.starter.datasource.DatasourceApi;
import io.github.flypiggy.stack.operate.log.spring.boot.starter.model.LogDTO;
import io.github.flypiggy.stack.operate.log.spring.boot.starter.properties.Mongodb;
import io.github.flypiggy.stack.operate.log.spring.boot.starter.properties.enums.DateSuffixEnum;
import io.github.flypiggy.stack.operate.log.spring.boot.starter.utils.DateTimeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.mongodb.core.MongoTemplate;

public class MongodbRepository implements DatasourceApi {

    private final Logger logger = LoggerFactory.getLogger(MongodbRepository.class);

    private final MongoTemplate mongoTemplate;
    private final String baseCollectionName;
    private final String pattern;
    private final Boolean haveSuffix;

    public MongodbRepository(MongoTemplate mongoTemplate, Mongodb mongodb) {
        this.mongoTemplate = mongoTemplate;
        this.baseCollectionName = mongodb.getCollectionName();
        this.haveSuffix = mongodb.getSuffix() != null;
        this.pattern = haveSuffix ? DateSuffixEnum.getMongoSuffixPattern(mongodb.getSuffix()) : "";
    }

    @Override
    public void save(LogDTO logDTO) {
        String collectionName = haveSuffix
                ? this.baseCollectionName + DateTimeUtils.format(logDTO.getCreateTime(), pattern)
                : this.baseCollectionName;
        try {
            mongoTemplate.insert(logDTO, collectionName);
        } catch (Exception e) {
            logger.warn("OPERATE-LOG Mongo insert log record error.This exception will not affect your main program flow, but operation logging cannot be saved.", e);
        }
    }

}
